﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Model;

namespace SqlServerDAL
{
    public class BaseDAO<T> where T:class
    {
        MyETLockContext context = DbContextFactory.GetDbContext();        
        //新增的方法
        public void Add(T entity)
        {
            context.Set<T>().Add(entity);
        }
        //删除数据的方法
        public void Delete(T entity)
        {
            context.Entry(entity).State = EntityState.Deleted;
        }
        //修改的方法
        public void Update(T entity) 
        {
            context.Entry(entity).State = EntityState.Modified;
        }
        //查询数据的方法
        public List<T> GetList(Func<T, bool> lambadaWhere)
        {
            return context.Set<T>().Where(lambadaWhere).ToList();
        }
        //简单分页查询的方法
        public List<T> GetListByPageIndex<S>(Func<T, bool> lambadaWhere, Func<T, S> lambadaOrder, bool isAsc, int pageIndex, int pageSize, ref int count)
        {
            List<T> temp = context.Set<T>().Where(lambadaWhere).ToList();
            count = temp.Count;
            if (isAsc)
            {
                return temp.OrderBy(lambadaOrder)
                           .Skip((pageIndex - 1) * pageSize)
                           .Take(pageSize).ToList();
            }
            else
            {
                return temp.OrderByDescending(lambadaOrder)
                         .Skip((pageIndex - 1) * pageSize)
                         .Take(pageSize).ToList();
            }
        }

        //lambada多条件累加查询分页
        public List<T> GetListByPageIndexBy<S>(Expression<Func<T, bool>> where, Func<T, S> lambadaOrder, bool isAsc, int pageIndex, int pageSize, out int count)
        {
            List<T> temp = context.Set<T>().Where(where).ToList();
            count = temp.Count;
            if (isAsc)
            {
                return temp.OrderBy(lambadaOrder)
                           .Skip((pageIndex - 1) * pageSize)
                           .Take(pageSize).ToList();
            }
            else
            {
                return temp.OrderByDescending(lambadaOrder)
                         .Skip((pageIndex - 1) * pageSize)
                         .Take(pageSize).ToList();
            }
        }        

    }
}
